<script setup lang="ts">
import { homeApi } from '@/api/Api';
import { ref, onMounted, onBeforeUnmount } from 'vue';
import * as echarts from 'echarts';
import { DEV } from '../config/env';
import { WebsocketUtils } from 'gtl-utils/utils/websocket-utils'
const socket = ref<WebsocketUtils | null>();
const logins = ref([])

const diskDisplay = ref<any>();
const cpuDisplay = ref<any>();
const memoryDisplay = ref<any>();

// 单位换算
const getUnit = (value: number, index: number = 0):string=>{
    if((value / 1024) > 1){
        return getUnit((value / 1024) , index+1);
    }
    return value.toFixed(1)+["B", "K", "M", "G", "T"][index];
}

onMounted(()=>{
    /** 内存 */
    memoryDisplay.value = echarts.init(document.getElementById('memory'));
    memoryDisplay.value.setOption({
        title: {
            text: '内存使用量',
            left: 'center',
            textStyle: {
                fontSize: 13,                
                color: '#003340',
                top: 'top',
                fontWeight: 'bold', 
            }
        },
        grid: {
                height: '100%',
                width: '100%'
            },
        legend: {
            orient: 'vertical',
            left: 'left',
        },
        series: [
            {
                name: 'Access From',
                type: 'pie',
                radius: 80,
                data: [
                ],
                label: {
                    show: true,
                    position: 'inside',
                    formatter: (param: any)=>{
                        return param.name+"\n"+param.value+"MB";
                    }
                }
            }
        ],
        tooltip: {
          trigger: 'item',
          formatter: function (params: any) {
            console.log(params.value);
            return params.name+ ":"+params.value + "MB";
          }
        },

    });

    // 处理器
    cpuDisplay.value = echarts.init(document.getElementById("cpu"))
    let cpuOption: any = {
        grid: {
            left: '15%'
        },
        title: {
            text: "cpu使用率",
            left: "center",
            textStyle: {
                fontSize: 13,                
                color: '#003340',
                top: 'top',
                fontWeight: 'bold', 
            }
        },
        xAxis: {
            type: 'category',
            data: []
        },
        yAxis: {
            max: 100,
            type: 'value',
            axisLabel: {
                formatter: '{value}%'
            }
        },
        series: [
            {
            data: [],
            type: 'line'
            }
        ],
        tooltip: {
          trigger: 'item',
          formatter: function (params: any) {
            console.log(params.value);
            return params.value + "%";
          }
        },
    };
    cpuDisplay.value.setOption(cpuOption);
    const count =15;
    for(let i = 0;i < count;i++){
        let s = (count-i)*2+"s";
        cpuOption.xAxis.data.push(s);
        cpuOption.series[0].data.push(null);
    }

    // 磁盘使用量
    diskDisplay.value = echarts.init( document.getElementById("disk"))
    let diskOption: any = {
        title: {
            text: "磁盘使用量",
            left: 'center',
            textStyle: {
                fontSize: 13,
                color: '#003340',
                top: 'top',
                fontWeight: 'bold', 
            }
        },
        grid: {
            left: '15%'
        },
        xAxis: {
            data: [],
            axisLabel: {
                rotate: -36 // 设置纵坐标标签旋转角度为 -90 度，实现竖着显示
            }
        },
        yAxis: {
            max: 100,
            axisLabel: {
                formatter: '{value}%'
            }
        },
        axisLabel: {
            formatter: function (value: any, index: any) {
                if(value.length > 6){
                    return value.substr(0,6)+"..."
                }
                return value
            },
            rich: {
                style: {
                    textOverflow: 'elipsis',
                    fontSize: 11
                }
            }
        },
        series: [
            {
            barWidth: 28,
            type: 'bar',
            data: [],
            }
        ],
        visualMap: {
            show: false,
            pieces: [
                { min: 0, max: 79, color: '#00ff00' }, // 0 - 20 为绿色
                { min: 80, max: 100, color: '#ff0000' } // 41 - 60 为红色
            ]
        },        
        tooltip: {
          trigger: 'item',
          formatter: function (params: any) {
            console.log(params.value);
            let total = params.data.total;
            let free = params.data.free;
            return params.name+ "<br />已用:"+getUnit(total-free)+"<br />使用率:"+params.value+"%"+"<br/>可用:"+getUnit(free);
          }
        },
        label: {
            show: true,
            position: 'top',
            formatter: function (params: any) {
                let total = params.data.total;
                let free = params.data.free;
                return "已使用:"+getUnit(total-free)+"\n"+params.value+"%";
            }
        }
    };
    diskDisplay.value.setOption(diskOption);

    socket.value = new WebsocketUtils(DEV ? '/ws/ws/moniter/' : '/ws/moniter/');
    socket.value.debug = true;
    socket.value.onmessage( (data: any)=>{
        let sysinfo = JSON.parse(data.data);
        // 内存
        let used:any = Math.round(sysinfo.memory[3] / 1024 /1024 );
        let available:any = Math.round(sysinfo.memory[1]/ 1024 /1024 );
        let option: any = memoryDisplay.value.getOption();
        option.series[0].data[0] = {value: used, name: "已用内存" };
        option.series[0].data[1] = {value: available, name: "剩余内存" };
        memoryDisplay.value.setOption(option);

        // cpu 移动效果
        cpuOption.series[0].data.splice(0,1);
        cpuDisplay.value.setOption(cpuOption);
        cpuOption.series[0].data.push(sysinfo.cpu);
        cpuDisplay.value.setOption(cpuOption);

        // 磁盘
        let names: any = [];
        let datas: any = [];
        sysinfo.disk.forEach((d: any)=>{
            names.push(d.path.substr(d.path.lastIndexOf("/")+1));
            try{
                datas.push( {"value" : Math.round((d.total - d.free)/ d.total * 100), "total": d.total, "free": d.free});
            }catch(e){
                datas.push( 0);
            }
        })
        diskOption.xAxis.data = names;
        diskOption.series[0].data = datas;
        diskDisplay.value.setOption(diskOption);
    })
    setTimeout(()=>{
        socket.value?.send("sysinfo");
        socket.value?.addRecionnectSendMessage("callback", "sysinfo");
    }, 500)
    setTimeout(()=>{
        socket.value?.send("sysinfo");
        socket.value?.addRecionnectSendMessage("callback", "sysinfo");
    }, 1000)
    
    setTimeout(()=>{
        socket.value?.send("sysinfo");
        socket.value?.addRecionnectSendMessage("callback", "sysinfo");
    }, 2000)

})

onBeforeUnmount(()=>{
    socket.value?.close()
    socket.value = null;
    diskDisplay.value.dispose();
    memoryDisplay.value.dispose();
    cpuDisplay.value.dispose();
    cpuDisplay.value = null;
    memoryDisplay.value = null;
    diskDisplay.value = null;
    
})

homeApi.getLogins({
    page_index: 1, success: (data: any) => {
        logins.value = data
    }, fail: (err: any) => {
        console.log(err)
    }
})
</script>

<template>
    <div style="height: var(--ingres-top-bar); min-width: 1200px;">
        <div id="home-left-page" >
            <div style="height: 215px;">
                <div id="memory" style="width: 33%; height: 100%; float: left" ></div>
                <div id="cpu" style="width: 33%; height: 100%; float: left;"></div>
                <div id="disk" style="width: 33%; height: 100%; float: left;"></div>
            </div>
            <br/>
        </div>

        <div id="home-right-page">
            <el-card class="box-card" style="background-color: aliceblue; text-align: center;">
                <div class="text item">
                    在线用户
                </div>
            </el-card>
            <el-card class="box-card" v-for="o in logins" :key="o" style=" text-align: center;">
                <div class="text item">
                    {{ '用户:' + (<any>o).username }}<br />
                    {{ '邮箱:' + (<any>o).email }}<br />
                    {{ '上次登录时间:' + (<any>o).last_login }}<br />
                </div>
            </el-card>
        </div>
    </div>
</template>

<style scoped>
.home-left-header {
    float: left;
    height: 110px;
    padding: 10px;
    margin: 5px;
    width: calc(100% / 4 - 10px);
    box-shadow: var(--el-box-shadow-dark);
}

.home-left-header>div {
    width: 150px;
    height: 100%;
    background-color: #fff;
    display: flex;
    margin: auto;
    justify-content: center;
    align-items: center;
    box-shadow: var(--el-box-shadow);
}

.home-left-header>div>div {
    justify-self: center;
    text-align: center;
}

.home-left-header>div>div>span:nth-child(1) {
    background-color: #fff;
    height: 39px;
    font-size: 36px;
    color: rgba(86, 198, 198, 0.764);
}

#home-left-page {
    width: calc(100% - 350px);
    height: 100%;
    background-color: #bdbdbd7c;
    float: left;
}

#home-right-page {
    width: 350px;
    height: 100%;
    overflow-y: scroll;
    float: right;
}

::-webkit-scrollbar {
    width: 2px;
    background-color: #ffffff;


}

::-webkit-scrollbar-thumb {
    background-color: #636363d7;
}
</style>